<?php
declare (strict_types=1);

namespace app\admin\controller\article;

use app\admin\validate\CheckArticle;
use app\admin\model\article\ArticleCates;
use app\admin\model\article\Articles;
use app\common\controller\AdminBaseController;
use Jrk\Tool;
use Jrk\Tree;
use think\Request;
use app\admin\service\ExcelService;
use think\Exception;
use think\facade\Db;
use app\common\service\FormBuilder as Form;
use think\facade\Route;


class Article extends AdminBaseController
{
    protected $cate;

    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new Articles();

        $this->cate = Tree::toFormatTree(ArticleCates::where("model_id", "<>", 4)->select()->toArray(), "name");
        //查询不是链接模型的栏目
        $this->assign("cate", $this->cate);
    }



    /**
     * @return string|\think\response\Json
     * @throws \Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:添加
     */
    public function add()
    {
        $f = [];
        $f[] = Form::select('cate_id', '文章栏目')->setOptions(function () {
            $list = $this->cate;
            $options = [];
            foreach ($list as $k => $v) {
                $options[] = ['label' => $v['title_show'], 'value' => $v['id']];
            }
            return $options;
        })->multiple(false);
        $f[] = Form::input('title', '文章标题')->placeholder('请输入文章标题')->required("请输入文章标题")->autocomplete(true)->col(13);
        $f[] = Form::color('title_color', '标题颜色', '#0E0E0E')->col(12)->info("页面展示时候改变文章标题颜色");
        $f[] = Form::rate('range', '评分等级', 1)->showText(true)->col(12)->count(8);

        $f[] = Form::frameImageOne("img_url", "封面图：", Route::buildUrl('admin/AttachMents/getImagesOne', array('fodder' => 'img_url')))->icon('image')->height("500px")->width('60%')->spin(true);
        $f[] = Form::input('keywords', '关键词')->placeholder('关键词以英文逗号隔开')->required("请输入关键词")->autocomplete(true)->col(12)->info("关键词以英文逗号隔开");
        $f[] = Form::textarea('description', '文章摘要')->rows(5)->info('留空时默认截取内容的前100个字符')->placeholder("文章摘要");
        $f[] = Form::frame('content', '文章内容', Route::buildUrl('Temp/editormd', array('fodder' => 'content', 'id' => 0)))->icon('ionic')->width("90%")->height('600px')->frameTitle("文章内容");
        $f[] = Form::radio('is_show', '是否显示', 1)->options([['label' => '显示', 'value' => 1], ['label' => '不显示', 'value' => 0]])->col(12);
        $f[] = Form::radio('is_top', '是否置顶', 0)->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(12);
        $f[] = Form::input('author', '作者', self::$admin_info['username'])->info('文章的作者')->required("请填写文章作者")->col(12);
        $f[] = Form::number('hits', '点击量', '0')->min(0)->info('文章的阅读量')->col(12);
        $f[] = Form::input('origin', '文章来源', '原创')->info('文章的来源')->required("请填写文章来源")->col(12);
        $f[] = Form::input('url', '链接地址')->info('有来源的时候填写来源的地址')->col(12);
        $f[] = Form::radio('is_recommend', '是否推荐', 0)->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(12);
        $form = Form::make_post_form('添加文章', $f, Route::buildUrl('upAndAdd'));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }


    /**
     * @param $id
     * @return string|\think\response\Json
     * @throws \Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:编辑
     */
    public function edit($id)
    {

        $info = $this->model->where("id", $id)->find();
        if (!$info) {
            return parent::failed("未查询到数据");
        }
        $f = [];
        $f[] = Form::select('cate_id', '文章栏目',"{$info->getData('cate_id')}")->setOptions(function () {
            $list = $this->cate;
            $options = [];
            foreach ($list as $k => $v) {
                $options[] = ['label' => $v['title_show'], 'value' => $v['id']];
            }
            return $options;
        })->multiple(false);
        $f[] = Form::input('title', '文章标题',$info->getData('title'))->placeholder('请输入文章标题')->required("请输入文章标题")->autocomplete(true)->col(13);
        $f[] = Form::color('title_color', '标题颜色',$info->getData('title_color'))->col(12)->info("页面展示时候改变文章标题颜色");
        $f[] = Form::rate('range', '评分等级', $info->getData('range'))->showText(true)->col(12)->count(8);
        $f[] = Form::frameImageOne("img_url", "封面图：", Route::buildUrl('admin/AttachMents/getImagesOne', array('fodder' => 'img_url')),$info->getData('img_url'))->icon('image')->height("500px")->width('60%')->spin(true);
        $f[] = Form::input('keywords', '关键词',$info->getData('keywords'))->placeholder('关键词以英文逗号隔开')->required("请输入关键词")->autocomplete(true)->col(12)->info("关键词以英文逗号隔开");
        $f[] = Form::textarea('description', '文章摘要',$info->getData('description'))->rows(5)->info('留空时默认截取内容的前100个字符')->placeholder("文章摘要");
        $f[] = Form::frame('content', '文章内容', Route::buildUrl('Temp/editormd', array('fodder' => 'content', 'id' =>$info->getData('id'))),$info->getData('content'))->icon('ionic')->width("90%")->height('600px')->frameTitle("文章内容");
        $f[] = Form::radio('is_show', '是否显示',$info->getData('is_show'))->options([['label' => '显示', 'value' => 1], ['label' => '不显示', 'value' => 0]])->col(12);
        $f[] = Form::radio('is_top', '是否置顶',$info->getData('is_top'))->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(12);
        $f[] = Form::input('author', '作者',$info->getData('author'))->info('文章的作者')->required("请填写文章作者")->col(12);
        $f[] = Form::number('hits', '点击量',$info->getData('hits'))->min(0)->info('文章的阅读量')->col(12);
        $f[] = Form::input('origin', '文章来源',$info->getData('origin'))->info('文章的来源')->required("请填写文章来源")->col(12);
        $f[] = Form::input('url', '链接地址',$info->getData('url'))->info('有来源的时候填写来源的地址')->col(12);
        $f[] = Form::radio('is_recommend', '是否推荐',$info->getData('is_recommend'))->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(12);
        $f[] = Form::hidden("id", $info->getData('id'));
        $form = Form::make_post_form('添加文章', $f, Route::buildUrl('upAndAdd'));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }


    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:数据导出
     */
    public function export()
    {
        $param = $this->request->post();
        $where = [];
        if (isset($param['title']) && $param['title'] != '') {
            $where[] = ['title', 'like', "%" . $param['title'] . "%"];
        }

        if (!empty($param['isAsc']) && !empty($param['orderByColumn'])) {
            $order = "{$param['orderByColumn']} {$param['isAsc']}";
        }

        if (!empty($param['is_show']) && (int)$param['is_show'] != 0) {
            $status = (int)$param['is_show'] - 1;
            $where[] = ['is_show', '=', $status];
        }

        if (!empty($param['is_top']) && (int)$param['is_top'] != 0) {
            $status = (int)$param['is_top'] - 1;
            $where[] = ['is_top', '=', $status];
        }

        if (!empty($param['is_recommend']) && (int)$param['is_recommend'] != 0) {
            $status = (int)$param['is_recommend'] - 1;
            $where[] = ['is_recommend', '=', $status];
        }

        if (!empty($param['cate_id']) && (int)$param['cate_id'] != 0) {
            $child = getChildsRule(ArticleCates::select()->toArray(), $param['cate_id'], false);
            $child[] = $param['cate_id'];
            $where[] = ['cate_id', 'in', $child];
        }

        if (isset($param['time']) && $param['time'] != '') {
            $ck = @explode(" ~ ", $param['time']);
            $b = $ck[0] . " 00:00:00";
            $e = $ck[1] . " 23:59:59";
            $where[] = ['create_time', 'between', [strtotime($b), strtotime($e)]];
        }

        $result = $this->model->with("cates")->limit_select($where, $order);

        if (empty($result)) {
            return parent::JsonReturn("根据条件未查询到数据", 0);
        }

        $doman = \request()->domain();
        $arr = [];
        foreach ($result as $k => $v) {
            $v['is_top'] == 1 ? $top = '是' : $top = '否';
            $v['is_recommend'] == 1 ? $re = '是' : $re = '否';
            $arr[] = [
                $v['id'], $v['cates']['name'], $v['title'], $v['description'], $v['keywords'], $doman . $v['img_url'], $v['author']
                , $v['origin'], $v['hits'], $v['love']
                , $top, $re, $doman . $v['url']
                , $v['comment_num'], $v['content'], $v['create_time']
            ];
        }
        $filename = ExcelService::setExcelHeader(['ID', '文章栏目', '文章标题', '文章描述', '关键词', '封面图', '作者', '来源', '点击量', '喜欢量', '置顶', '推荐', '地址', '评论量', '内容', '时间'])
            ->setExcelTile('文章数据', '文章数据', date('Y-m-d H:i:s', time()))
            ->setExcelContent($arr)
            ->ExcelReturn();
        return parent::JsonReturn($filename);
    }


    /**
     * @return string
     * @throws \Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @describe:回收站
     */
    public function recycle()
    {
        if (IS_AJAX) {
            return $this->model->getRecycleData($this->param);
        }
        return $this->fetch();
    }


    /**
     * @return mixed
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:真实删除
     */
    public function deltrue()
    {
        if (IS_AJAX) {
            $ids = $this->request->post("ids");

            return $this->model->delTrue($ids);
        }
    }


    /**
     * @return mixed
     * @author: Hhy <jackhhy520@qq.com>
     * @describe:恢复数据
     */
    public function recycleData()
    {
        if (IS_AJAX) {
            $ids = $this->request->post("ids");
            return $this->model->recycleData($ids);
        }
    }


}
